import preferences from '@ohos.data.preferences';
import Contact from './PreferencesUtil'

class PreferencesUtil{

  prefMap: Map<String, preferences.Preferences> = new Map()

  async loadPreference(context, name : string){
    try {
      let pref = await preferences.getPreferences(context, name)
      this.prefMap.set(name, pref)
      console.log('testTag', '加载Prefers',name,'加载成功')
    }catch (reason){
      console.log('testTag', '加载Prefers',name,'加载失败',JSON.stringify((reason)))
    }
  }

  async putPreferenceValue(name: string, key: string, value: preferences.ValueType){
    if(!this.prefMap.has(name)){
      console.log('testTag', 'Preference[${name}]尚未初始化！')
      return
    }
    try {
      let pref = this.prefMap.get(name)
      await pref.put(key, value)
      await pref.flush()
      console.log('testTag', '保存Prefers',name,key,'=',value,'成功')
    } catch (reason) {
      console.log('testTag', '保存Prefers',name,key,'=',value,'失败',JSON.stringify((reason)))
    }
  }

  async getPreferenceValue(name: string, key: string, defaultValue: preferences.ValueType){
    if(!this.prefMap.has(name)){
      console.log('testTag', 'Preference',name,'尚未初始化！')
      return
    }
    try {
      let pref = this.prefMap.get(name)
      let value = await pref.get(key, defaultValue)
      console.log('testTag', '读取Prefers',name,key,'=',value,'成功')
      return value
    } catch (reason) {
      console.log('testTag', '读取Prefers',name,key,'失败',JSON.stringify((reason)))
    }
  }
}

const preferencesUtil = new PreferencesUtil()

export default  preferencesUtil as PreferencesUtil